from datetime import datetime
from flask import render_template, session, redirect, url_for, flash, current_app
from app.main import main
from app.main.forms import NameForm
from app import db
from app.models import User
from app.email import send_email


@main.route('/', methods=['GET', 'POST'])
def index():
    # name = None
    nameform = NameForm()
    if nameform.validate_on_submit():
        user = User.query.filter_by(username=nameform.name.data).first()
        if user is None:
            user = User(username=nameform.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
            flash('很高兴见到你', 'danger')
            if current_app.config['FLASKY管理员']:
                send_email(current_app.config['FLASKY管理员'],'新用户', 'mail/new_user', user=user)
        else:
            session['known'] = True
            flash('很荣幸再见到你', 'success')
        # old_name = session.get('name')
        # if old_name is not None and old_name != nameform.name.data:
        #     flash('你修改了姓名！', 'danger')
        session['name'] = nameform.name.data
        nameform.name.data = ''
        return redirect(url_for('main.index'))
    return render_template('index.html', name=session.get('name'), nameform=nameform,known=session.get('known', False), current_time=datetime.utcnow())